package pers.leeyns.rd.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import pers.leeyns.rd.entity.Dictionary;

public class DictionaryUtils {
	
	private static Map<String,Object> cache = new HashMap<String,Object>();
	

	
	
	public static List<String> readLine(String fileName) throws IOException{
		InputStream is = DictionaryUtils.class.getClass().getResourceAsStream("/"+fileName);
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		String line = null;
		List<String> lines = new ArrayList<String>();
		while((line = br.readLine()) != null){
			lines.add(line);
		}
		return lines;
	}
	
	
	public static List<Dictionary> getZHCNDictionary(){
		List<Dictionary> list = new ArrayList<Dictionary>();
		try {
			List<String> lines = readLine("zh_cn.dict");
			if(lines != null && lines.size() > 0){
				for(String s:lines){
					String [] dict = s.split("=");
					if(dict != null && dict.length > 1){
						list.add(new Dictionary(dict[0],dict[1]));
					}else if(dict != null && dict.length == 1){
						list.add(new Dictionary(dict[0], null));
					}else{
						list.add(new Dictionary(s, null));
					}
				}
			}
		
		} catch (IOException e) {
		}
		return list;
	}
	
	public static String getZHCNResource(){
		Object object = getCache(CacheKey.ZH_CN_KEY);
		if(object != null){
			return (String) object;
		}
		List<Dictionary> list = getZHCNDictionary();
		String str = null;
		if(list != null && list.size() > 0){
			StringBuffer sb = new StringBuffer();
			for(int i =0;i<list.size();i++){
				Dictionary dict = list.get(i);
				if(dict.getVal() != null && dict.getVal().length() > 0){
					sb.append(dict.getVal());
				}
			}
			str = sb.toString();
		}
		addCache(CacheKey.ZH_CN_KEY,str);
		return str;
	}
	
	public static List<Dictionary> getENDictonary(){
		
		return null;
	}
	
	
	public static synchronized Object  getCache(String key){
		return cache.get(key);
	}
	
	public static synchronized Object  addCache(String key,Object value){
		return cache.put(key, value);
	}
	
	public static class CacheKey{
		public static String ZH_CN_KEY = "zh_cn_key";
	}
	
	public static void main(String[] args) throws InstantiationException, IllegalAccessException {
		System.out.println();
	}
}
